<template>
    <div>
        <h1>购物车</h1>
        <Control></Control>
        <ul>
            <li v-for="(f,i) of state" :key="i">
                {{f.name}}
                单价：{{f.price}}
                <Counter 
                    :many="f.many"
                    :index="i"
                    @add="add"
                    @sub="sub"
                ></Counter>
            </li>
        </ul>
        <h2>总价：{{totalPrice}}</h2>
    </div>
</template>

<script>
    import Counter from "./Counter"
    import Control from "./Control"
    import store from "../store"
    export default {
        components:{
            Counter,
            Control
        },
        data(){
            return{
                state:store.state.fruits
            }
        },
        methods:{
            add(index){
                store.state.fruits[index].many++;
            },
            sub(index){
                if(store.state.fruits[index].many>0){
                    store.state.fruits[index].many--;
                }
            }
        },
        computed:{
            totalPrice(){
                let total_price = 0;
                this.state.forEach(data => {
                    total_price = (data.many * data.price) + total_price
                })
                return total_price.toFixed(2)
            }
        }
    }
</script>